class ApiController < ApplicationController

  # respond_to :json
# skip_before_filter :verify_authenticity_token, :only => :create
skip_before_filter :verify_authenticity_token


 before_filter :configure_permitted_parameters, if: :devise_controller?

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:create) { |u| u.permit(:email, :password) }
end
#http://jessewolgamott.com/blog/2012/01/19/the-one-with-a-json-api-login-using-devise/
  def index
    render :json=> {:success=>true, :status=>200, :env => Rails.env}
  end

  def create
    @user = User.new(:email=>params[:user][:email],:password=>params[:user][:password])
    p @user
    if @user.save
      render :json=> {:success=>true, :status=>202, :email=>@user.email,:token=>@user.authentication_token}
      return
    else
      warden.custom_failure!
      render :json=> {:success=>false, :status=>422, :info => @user.errors}
    end

  end

  def login
    # build_resource
    resource = User.find_for_database_authentication(:email=>params[:user][:email])
    print params
    return invalid_login_attempt unless resource
    puts resource.authentication_token
    if resource.valid_password?(params[:user][:password])
      resource.save
      # sign_in("user", resource)
      # print resource
      render :json=> {:success=>true, :status=>200, :email=>resource.email, :token=>resource.authentication_token}
      return
    end
    invalid_login_attempt
  end

  def writedata
    user = User.find_for_database_authentication(:authentication_token=>params[:token])
    return invalid_login_attempt unless user

    data = DataStore.where(:user_id=>user,:key => params[:key]).first_or_initialize
    data.update_attributes({
      :value => params[:value]
      })
    render :json=> {:success=>true, :status=>200}
  end

  def getdata
    user = User.find_for_database_authentication(:authentication_token=>params[:token])
    return invalid_login_attempt unless user

    data = DataStore.where(:user_id=>user,:key => params[:key])
    if !data.empty?
      render :json=> {:success=>true, :status=>200, :data => data}
    else
      render :json=> {:success=>true, :status=>200, :data => nil}
    end
end

  def savefile
    @@BUCKET = "box.epiid.dev"
    AWS::S3::DEFAULT_HOST.replace "s3-ap-southeast-1.amazonaws.com"

    resource = User.find_for_database_authentication(:authentication_token=>params[:token])
    return invalid_login_attempt unless resource

    # save file to server
    # reading file and generate to unique md5
    print params[:name]
    upload = params[:upload]
    orig_filename =  params[:filedata].original_filename
    ext = File.extname(orig_filename)
    # md5_filename = Digest::MD5.file(params[:filedata].read)
    filename = sanitize_filename(orig_filename)
    directory = "public/data"
    path = File.join(directory, filename)
    File.open(path, "wb") { |f| f.write(params[:filedata].read)}
    md5_filename = Digest::MD5.file(path).to_s

    #upload to S3 with md5 name
    AWS::S3::S3Object.store("#{resource.id}-#{md5_filename}#{ext}", open(path), @@BUCKET, :access => :public_read)
    url = AWS::S3::S3Object.url_for("#{resource.id}-#{md5_filename}#{ext}", @@BUCKET, :authenticated => false)

    #save to database
    @databox = DataBox.new(owner_id: resource.id,filename: "#{resource.id}-#{md5_filename}#{ext}",original_filename: filename,data_type: 1)
    @databox.save

    render :json=> {:success=>true, :status=>200, :url=>url}
  end


  def forget_password_step1
    #1. app trigger user forget password
    #2. email send to user email address
    #3. user need to click link and go to web site to key in password twice


    # check whether account exists?

    resource = User.find_for_database_authentication(:email=>params[:user][:email])
    return invalid_login_attempt unless resource

    # generate reset pass token, write to db and also the last update to ensure 24 hours.
    # data = ResetPasswordToken.where(:user_id=>resource).first_or_initialize
    # randomToken = ('a'..'z').to_a.shuffle[0,16].join
    # data.update_attributes({
    #   :resetToken => randomToken,
    #   :expiredate => DateTime.now + 1
    # })

    # sending email
    # UserMailer.forget_password_email(randomToken).deliver
    resource.send_reset_password_instructions
    # response email status
    render :json=>{:success=>true, :status=>201, :message=>"sent out email"}
  end

  def destroy
    sign_out(resource_name)
  end

  #private api for getting user information directly from inkcase photo and lifebalanz server

  def private_user_verification
    # Validate private service token to prove Friendly


    # providing user token. return user id.
    @user = User.find_for_database_authentication(:authentication_token=>params[:usertoken])
    return invalid_token_attempt unless @user
    render :json=> {:success=>true, :status=>202, :email=>@user.email,:id=>@user.id, :token=>@user.authentication_token}
  end

  private
  def sanitize_filename(file_name)
      just_filename = File.basename(file_name)
      just_filename.sub(/[^\w\.\-]/,'_')
  end

  protected
  def ensure_params_exist
    return unless params[:user_login].blank?
    render :json=>{:success=>false, :status=>422, :message=>"missing user_login parameter"}
  end

  def invalid_login_attempt
    warden.custom_failure!
    render :json=> {:success=>false, :status=>401, :message=>"Error with your login or password"}
  end

  def invalid_token_attempt
    warden.custom_failure!
    render :json=> {:success=>false, :status=>401, :message=>"Error with your token"}
  end
end
